package com.platform.api;

import com.alibaba.fastjson.JSON;
import com.platform.annotation.IgnoreAuth;
import com.platform.entity.UserVo;
import com.platform.service.ApiUserService;
import com.platform.util.ApiBaseAction;
import com.platform.util.CheckSumBuilder;
import com.alibaba.fastjson.JSONObject;
import com.platform.util.DateUtils;
import com.platform.utils.RRException;
import com.qiniu.util.Json;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.IOUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by zhurusen on 2018/6/8
 * 作者: @author zhurusen <br>
 */
@RestController
@RequestMapping(value = "/api/route")
public class RouteController extends ApiBaseAction {

    @Autowired
    private ApiUserService apiUserService;

    private static final Log log = LogFactory.getLog(RouteController.class);
    // 需要改成自身应用的appSecret
    private final String appSecret = "54b1e8eeca05";

    @IgnoreAuth
    @RequestMapping("mock")
    public JSONObject mockClient(HttpServletRequest request)
            throws Exception {
        System.out.println("==========登录登出回调==========");
        JSONObject result = new JSONObject();
        try {
            // 获取请求体
            byte[] body = readBody(request);
            if (body == null) {
//                log.warn("request wrong, empty body!");
                result.put("code", 414);
                return result;
            }
            // 获取部分request header，并打印
            String ContentType = request.getContentType();
            String AppKey = request.getHeader("AppKey");
            String CurTime = request.getHeader("CurTime");
            String MD5 = request.getHeader("MD5");
            String CheckSum = request.getHeader("CheckSum");
            // 将请求体转成String格式，并打印
            String requestBody = new String(body, "utf-8");
//            log.info("____________" + requestBody);
            // 获取计算过的md5及checkSum
            String verifyMD5 = CheckSumBuilder.getMD5(requestBody);
            String verifyChecksum = CheckSumBuilder.getCheckSum(appSecret, verifyMD5, CurTime);
            // TODO: 比较md5、checkSum是否一致，以及后续业务处理
            JSONObject jsonObject = JSON.parseObject(requestBody);

            String accid = jsonObject.getString("accid");
            String eventType = jsonObject.getString("eventType");

            if (accid != null && !accid.isEmpty()) {
                UserVo userVo = apiUserService.queryByMobile(accid);
                if (userVo != null && userVo.getOnline_status() != 3) {

                    /**
                     * 登出
                     */
                    if (eventType != null && eventType.equals("3")) {
                        userVo.setOnline_status(4);
                        //计算在线时长
                        Integer shichang = DateUtils.getDiffDays(userVo.getLast_login_time(), new Date());
                        userVo.setOlinetime(userVo.getOlinetime().add(new BigDecimal(shichang)));
                    }
                    /**
                     * 登陆
                     */
                    if (eventType != null && eventType.equals("2")) {
                        userVo.setOnline_status(1);
                        userVo.setLast_login_time(new Date());
                    }
                    apiUserService.update(userVo);
                }
            }
            result.put("code", 200);
            return result;
        } catch (Exception ex) {
//            log.error(ex.getMessage(), ex);
            result.put("code", 414);
            return result;
        }
    }

    private byte[] readBody(HttpServletRequest request) throws IOException {
        if (request.getContentLength() > 0) {
            byte[] body = new byte[request.getContentLength()];
            IOUtils.readFully(request.getInputStream(), body);
            return body;
        } else {
            return null;
        }

    }
}
